#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File:hash_check.py
@Author:Josco
@Date:2022/09/27 17:42:39
@Version:1.0
@Description: 构建文件或者字符串的hash校验函数
'''
import hashlib
from bitarray import bitarray

class hash_check(object):
    def __init__(self) -> None:
        pass

    # 生成字符串的MD5值
    def md5(self, strdata):
        if strdata is None:
            return ''
        md5gen = hashlib.md5()
        md5gen.update(strdata.encode())
        md5code = md5gen.hexdigest()
        md5gen = None
        return md5code
    
    # 生成文件的MD5值
    def md5_file(self, filename):
        if filename is None:
            return ''
        md5gen = hashlib.md5()
        with open(filename, 'wb') as fd:
            data = fd.read()
        md5gen.update(data)
        md5code = md5gen.hexdigest()
        md5gen = None
        return md5code
    
    # 生成字符串的SHA256值
    def sha256(self, strdata):
        if strdata is None:
            return ''
        sha256gen = hashlib.sha256()
        sha256gen.update(strdata.encode())
        sha256code = sha256gen.hexdigest()
        sha256gen = None
        return sha256code
    
    # 生成文件的SHA256值
    def sha256_file(self, filename):
        if filename is None:
            return ''
        sha256gen = hashlib.sha256()
        with open(filename, 'wb') as fd:
            data = fd.read()
        sha256gen.update(data)
        sha256code = sha256gen.hexdigest()
        sha256gen = None
        return sha256code
    
    # 字符串转bits
    def str2bitarray(self,msg):  # msg 为str
        msg_2 = ""  # 转为1010拼接成字符串
        for a in msg.encode('utf-8'):
            a_16 = hex(a)[2:] # ascll 码16进制 str

            a_10 = int("1" + a_16, 16)  # 10进制 int, 防止转二进制最高为0丢失, 所以最高位前加1 , 10进制 int
            a_2 = bin(a_10)[3:] # 二进制 str, 利用ascll码值是8bit, 最前面可以加1,  在切片,去掉
            msg_2 += a_2
        # return bitarray(msg_2)
        return msg_2
    # bits转字符串
    def bitarray2str(self,bitarray_obj):  #  bitarray 转str
        bitarray_obj = bitarray(bitarray_obj)
        return str(bitarray_obj.tobytes())
        
